package com.example.file_upload.controller;

import com.example.file_upload.service.FileService;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Path;

@RestController
@RequestMapping("/file")
public class FileController {
    private FileService service;
    public FileController(FileService service){
        this.service=service;
    }


    @RequestMapping(value = "upload",method = RequestMethod.POST)
    public String uploadFile(@RequestParam("file")MultipartFile file) throws IOException{
        return service.saveFile(file);
    }


    @RequestMapping(value = "upload-multi",method = RequestMethod.POST)
    public String uploadFileMulti(@RequestParam("files")MultipartFile[] files) throws IOException{
        return service.saveMultiparFile(files);
    }


    @RequestMapping(value = "/download/{filename}",method = RequestMethod.GET)
    public ResponseEntity<Resource> download(@PathVariable String filename) throws IOException{
        Path file=service.getFilePath(filename);
        Resource resource=new UrlResource(file.toUri());

        if (resource.exists()){
            return ResponseEntity.ok()
                    .header("Content-Disposition","attachment:filename=\""+resource.getFilename()+"\"")
                    .body(resource);
        }
        return ResponseEntity.notFound().build();
    }
}
